package com.party.jackclientandroid.utils;

import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;

import com.party.jackclientandroid.R;

public class SoundPoolUtils {
    Context mContext;
    SoundPool mSoundPool;
    float audioMaxVolumn;
    float volumnCurrent;
    float volumnRatio;
    int soundID;
    int streamID;

    public SoundPoolUtils(Context context) {
        mContext = context;
        AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        audioMaxVolumn = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        volumnCurrent = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        volumnRatio = volumnCurrent / audioMaxVolumn;
        // 初始化SoundPool
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            AudioAttributes aab = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .build();
            mSoundPool = new SoundPool.Builder()
                    .setMaxStreams(10)
                    .setAudioAttributes(aab)
                    .build();
        } else {
            mSoundPool = new SoundPool(60, AudioManager.STREAM_MUSIC, 8);
        }
        mSoundPool = new SoundPool(60, AudioManager.STREAM_MUSIC, 8);
        //设置资源加载监听
        mSoundPool.setOnLoadCompleteListener(new MyOnLoadCompleteListener());
    }

    /**
     * 加载音频并且播放
     */
    public void loadNeedVoice() {
        // 加载ssets里面音频文件
//        mSoundPool.load(mContext.getAssets().openFd("biaobiao.mp3") , 1);
        soundID = mSoundPool.load(mContext, R.raw.redpack_open, 1);
    }

    class MyOnLoadCompleteListener implements SoundPool.OnLoadCompleteListener {
        /**
         * 第一个参数为播放音频ID
         * 第二个为左声道音量 第三个为右声道音量
         * 第四个为优先级
         * 第五个为是否循环播放
         * 第六个设置播放速度
         * 返回值 不为0即代表成功
         */
        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
            streamID = mSoundPool.play(soundID, volumnRatio, volumnRatio, 1, 0, 1);
        }
    }
}
